package bma.common.netty.webserver.common;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.jboss.netty.handler.codec.http.HttpRequest;

import bma.common.langutil.http.QueryStringDecoder;
import bma.common.netty.webserver.RequestForm;

public class RequestFormCommon implements RequestForm {

	protected HttpRequest request;

	protected QueryStringDecoder qsGET;
	protected QueryStringDecoder qsPOST;

	public RequestFormCommon(HttpRequest request) {
		super();
		this.request = request;
	}

	public QueryStringDecoder sureGET() {
		if (qsGET == null) {
			qsGET = new QueryStringDecoder(request.getUri());
		}
		return qsGET;
	}

	public QueryStringDecoder surePOST() {
		if (qsPOST == null) {
			qsPOST = new QueryStringDecoder(request.getUri());
		}
		return qsPOST;
	}

	@Override
	public String getValue(String name) {
		return sureGET().getParameter(name);
	}

	@Override
	public List<String> getValus(String name) {
		return sureGET().getParameters(name);
	}

	@Override
	public Set<String> getNames() {
		return sureGET().getParameters().keySet();
	}

	@Override
	public String postValue(String name) {
		return surePOST().getParameter(name);
	}

	@Override
	public List<String> postValus(String name) {
		return surePOST().getParameters(name);
	}

	@Override
	public Set<String> postNames() {
		return surePOST().getParameters().keySet();
	}

	@Override
	public String requestValue(String name) {
		String v = surePOST().getParameter(name);
		if (v != null) {
			return v;
		}
		return sureGET().getParameter(name);
	}

	@Override
	public List<String> requestValus(String name) {
		List<String> r = surePOST().getParameters(name);
		if (r != null && !r.isEmpty()) {
			return r;
		}
		return sureGET().getParameters(name);
	}

	@Override
	public Set<String> requestNames() {
		HashSet<String> r = new HashSet<String>();
		r.addAll(sureGET().getParameters().keySet());
		r.addAll(surePOST().getParameters().keySet());
		return r;
	}

}
